﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using RabbitMQ.Client;

namespace ConsoleAppFramework.Rmq
{
    public abstract class RmqBatchComsumerWorkBase<T>
    {
        protected string QueueName { get; set; }

        protected int BatchSize { get; set; } = 100;


        public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(3.0);


        protected RmqUrlEnum RmqUrl { get; set; }

        public void Run()
        {
            while (true)
            {
                Start();
                Console.WriteLine("运行了一轮数据!");
            }
        }

        public void Start()
        {
            List<T> list = new List<T>();
            DateTime dateTime = DateTime.Now.Add(Interval);
            try
            {
                using IModel model = RmqConnectPoolFactory.GetClientPool(RmqUrl).GetConnect().GetChannel();
                while (list.Count < BatchSize && !(DateTime.Now > dateTime))
                {
                    BasicGetResult basicGetResult = model.BasicGet(QueueName, autoAck: true);
                    if (basicGetResult == null)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }

                    _ = basicGetResult.DeliveryTag;
                    T item = JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(basicGetResult.Body));
                    list.Add(item);
                }
            }
            catch (Exception ex)
            {
                RmqLogHelper.WriteError("RmqBatchComsumerWorkBase 异常：" + ex.ToString());
            }

            if (list.Count > 0)
            {
                InternalHandleComingMessage(list);
            }
        }

        private bool InternalHandleComingMessage(List<T> messageDTO)
        {
            try
            {
                return HandleComingMessage(messageDTO);
            }
            catch (Exception ex)
            {
                RmqLogHelper.WriteError("InternalHandleComingMessage 消费队列异常：" + ex.Message);
                return false;
            }
        }

        protected abstract bool HandleComingMessage(List<T> messageDTO);
    }
}
